import { fileURLToPath, URL } from 'node:url'
import { resolve } from 'path'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { visualizer } from 'rollup-plugin-visualizer'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
	const config = {
		plugins: [vue()],
		resolve: {
			alias: {
				'@': resolve(__dirname, './src'),
			},
		},
		build: {
			// 生产环境构建配置
			minify: 'terser',
			terserOptions: {
				compress: {
					drop_console: true,
					drop_debugger: true,
				},
			},
			// 分块策略
			rollupOptions: {
				output: {
					manualChunks: {
						// 将大依赖包单独拆分
						'element-plus': ['element-plus'],
						'vue-vendor': ['vue', 'vue-router', 'pinia'],
						editor: ['@wangeditor/editor', '@wangeditor/editor-for-vue'],
						echarts: ['echarts'],
					},
					// 控制chunk大小
					chunkFileNames: 'assets/js/[name]-[hash].js',
					entryFileNames: 'assets/js/[name]-[hash].js',
					assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
				},
				// 设置chunk大小警告阈值
				chunkSizeWarningLimit: 1500,
			},
		},
		server: {
			// 开发服务器配置
			port: 3000,
			host: '0.0.0.0',
			open: true,
			proxy: {
				// API代理
				'/api': {
					target: 'http://localhost:8080',
					changeOrigin: true,
				},
			},
		},
	}

	// 如果是分析模式，添加分析插件
	if (mode === 'analyze') {
		config.plugins.push(
			visualizer({
				open: true,
				filename: 'dist/stats.html',
				gzipSize: true,
				brotliSize: true,
			})
		)
	}

	return config
})
